package YAPserver.collisionEngine;

import YAPserver.gameObjects.Line;
import YAPserver.gameObjects.Point;

public class Collision {
	/**
	 * Detects collisions that happen in the next round.
	 * @param ball
	 * @param wall
	 * @return
	 */
	public static boolean detect(Ball ball, Wall wall){
		
		if(ball.getLine().hasIntersection(wall.getLine())){
			return true;
		}
		
		double distance = ball.getNextMiddlePoint().distance(wall.getLine());
		if(distance <= ball.getRadius()){
			Point point = new Point(wall.getNormal());
			point.scalarMult(-ball.getRadius());
			Line line = new Line(ball.getMiddlePoint(), ball.getMiddlePoint().add(point));
			if(line.hasIntersection(wall.getLine())){
				return true;
			}
			
			//check if near endPoints
			distance = ball.getNextMiddlePoint().distance(wall.getEndPoint());
			if(distance <= ball.getRadius()){
				return true;
			}
			distance = ball.getNextMiddlePoint().distance(wall.getStartPoint());
			if(distance <= ball.getRadius()){
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Returns the point of intersection between a ball and a wall.
	 * @param ball ball that intersects a wall
	 * @param wall wall that has been intersected
	 * @return the point of intersection
	 */
	public static Point intersection(Ball ball, Wall wall){
		Point wallStart = wall.getStartPoint();
		Point wallEnd = wall.getEndPoint();
		Point ballStart = ball.getMiddlePoint();
		Point ballEnd = ball.getNextMiddlePoint();
		if(ballEnd.distance(wall.getLine()) <= ball.getRadius()){
			Point point = new Point(wall.getNormal());
			point.scalarMult(-ball.getRadius());
			ballEnd = ball.getMiddlePoint().add(point);
		}
		double mObject = (wallStart.getYPos()-wallEnd.getYPos()) / (wallStart.getXPos()-wallEnd.getXPos());
		double mBall = (ballStart.getYPos()-ballEnd.getYPos()) / (ballStart.getXPos()-ballEnd.getXPos());
		
		double cObject = wallStart.getYPos() - mObject*wallStart.getXPos();
		double cBall = ballStart.getYPos() - mBall*ballStart.getXPos();
		
		double x;
		double y;
		if(ballStart.getXPos()-ballEnd.getXPos() == 0){
			x = ballStart.getXPos();
			y = mObject*x + cObject;
		}else if(wallStart.getXPos()-wallEnd.getXPos() == 0){
			x = wallStart.getXPos();
			y = mBall*x + cBall;
		}else{	
			x = (cObject - cBall)/(mBall - mObject);
			y = (cObject*mBall - cBall*mObject)/(mBall - mObject);
		}
		return new Point(x,y);
	}
}
